<template>
	<div class="ll-page">
		<div v-if="isBannerContentClose" class="banner-tips">
			<div class="banner-tips-content">
				<img class="banner-tips-content-bg" src="~@/assets/images/img_ts_bg_long.png" alt="" />
				<h1>Banner管理说明</h1>
				<div class="banner-tips-content-box" :class="isBannerContentOpen ? '' : 'close'">
					<p>* 站点展示位置在C端商城实际只展示当前展示位置上线Banner中前10个Banner</p>
					<p>
						* 已下线Banner请点击右侧“查看历史Banner”按钮查看
						<span
							v-if="!isBannerContentOpen"
							class="banner-tips-content-box-btn"
							@click="isBannerContentOpen = true"
						>
							展开
						</span>
					</p>
					<p>* 列表数据为当前banner的汇总数据，如需查看每日数据，请点击查看详情</p>
					<p>
						* 更换图片素材不影响数据统计，可通过每日数据对比素材点击效果
						<span
							v-if="isBannerContentOpen"
							class="banner-tips-content-box-btn"
							@click="isBannerContentOpen = false"
						>
							收起
						</span>
					</p>
				</div>
				<img
					class="banner-tips-content-close"
					src="~@/assets/images/icon_ts_close.png"
					alt=""
					@click="isBannerContentClose = false"
				/>
			</div>
		</div>
		<div style="padding: 10px 10px 0 10px">
			<n-button type="info" @click="addBanner">新增banner</n-button>
			<n-button style="margin-left: 6px" @click="seeHistoryBanner">查看历史banner</n-button>
		</div>
		<!-- S 查询 -->
		<div class="ll-page-query flex">
			<n-form
				inline
				:model="searchForm"
				label-placement="left"
				:show-feedback="false"
				class="flex-1 flex-wrap"
			>
				<n-form-item label="事业群：" path="causeId">
					<n-select
						v-model:value="searchForm.configId"
						:options="configOptions"
						placeholder="请选择"
						filterable
						class="w-193px"
						@update:value="causeIdChange"
					/>
				</n-form-item>
				<n-form-item label="站点：" path="locationId">
					<n-select
						v-model:value="searchForm.locationId"
						:options="locationOptions"
						placeholder="请选择"
						filterable
						class="w-193px"
						@update:value="getList"
					/>
				</n-form-item>

				<n-form-item label="展示位置：" path="positionType">
					<n-select
						v-model:value="searchForm.positionType"
						:options="positionTypeOption"
						class="w-193px"
						@update:value="getList"
					/>
				</n-form-item>

				<n-form-item label="投放渠道:" path="channel">
					<n-select
						v-model:value="searchForm.channel"
						:options="channelOption"
						class="w-193px"
						@update:value="getList"
					/>
				</n-form-item>
				<n-form-item>
					<n-button color="rgba(0, 0, 0, 0.1)" text-color="#333333" @click="handelReset">
						重置
					</n-button>
				</n-form-item>
			</n-form>
			<div>
				<n-input
					v-model:value="searchForm.keyWord"
					placeholder="请输入Banner ID/产品ID/产品名称"
					style="width: 320px"
					:disabled="sort"
					@keydown.enter="getList"
				>
					<template #suffix>
						<img
							src="@/assets/images/icon_symbol_search@2x.png"
							alt=""
							style="width: 18px; height: 18px"
						/>
					</template>
				</n-input>
			</div>
		</div>
		<div class="type">
			<div class="type-box">
				<template v-for="(item, index) in typeOptions" :key="item.value">
					<div
						class="type-box-item"
						:class="[
							index === typeCurrentIndex ? 'isActive' : '',
							index !== 0 && sort ? 'notClick' : ''
						]"
						@click="typeChange(index)"
					>
						{{ item.label }}
					</div>
				</template>
			</div>
			<div class="type-hr"></div>
		</div>
		<div class="mode-box">
			<div class="mode-box-item">
				<span>分析模式</span>
				<n-switch v-model:value="analysis" />
			</div>
			<div class="mode-box-item">
				<span>排序模式</span>
				<n-switch v-model:value="sort" />
			</div>
		</div>

		<!-- E 查询 -->
		<!-- S 表格 -->
		<div class="ll-page-table">
			<template v-if="analysis">
				<n-data-table
					:columns="analysisColumns"
					:data="tableData"
					:pagination="paginationReactive"
					:loading="tableLoading"
					:remote="true"
					flex-height
					:style="{ height: '100%' }"
					:scroll-x="2500"
				/>
			</template>
			<template v-else>
				<n-data-table
					:columns="defaultColumns"
					:data="tableData"
					:loading="tableLoading"
					:pagination="paginationReactive"
					:remote="true"
					flex-height
					:style="{ height: '100%' }"
				/>
			</template>
		</div>
		<bannerDetails ref="bannerDetailsRef" @commit="getList"></bannerDetails>
		<!-- E 表格 -->
		<n-modal
			v-model:show="OfflineShow"
			preset="dialog"
			title="确定下线"
			content="确定下线Banner？"
			:show-icon="false"
			:mask-closable="false"
			negative-text="取消"
			positive-text="下线"
			@positive-click="ConfirmOffline"
		/>
	</div>
</template>

<script setup>
import { h, reactive, ref, watch, nextTick } from 'vue';
import { NButton, NImage, useMessage, useDialog } from 'naive-ui';
import { NTooltip } from 'naive-ui';
import bannerDetails from './components/bannerDetails.vue';
import {
	locationAllList,
	locationconfAll,
	tdBannerList,
	areaTdBannerList,
	tdBannerMove,
	tdBannerOffline,
	bannerDetail
} from '@/api/bannerMange';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter();
const route = useRoute();
const bannerDetailsRef = ref();
const message = useMessage();
const dialog = useDialog();

const isBannerContentOpen = ref(true); //消息是否展开/收起
const isBannerContentClose = ref(true); //消息关闭
// 判断是否包含角色
const hasRoles = ref(false);
const roleIsAdmin = ref(false);

const typeCurrentIndex = ref(0); //当前选择
const typeOptions = [
	{ label: '全部', value: null },
	{ label: '展示中', value: 1 },
	{ label: '待展示', value: 2 }
];
const analysis = ref(false); //分析模式
const sort = ref(false); //排序模式
const searchForm = reactive({
	keyWord: null,
	channel: '',
	configId: '',
	locationId: '',
	status: null,
	positionType: ''
});
const positionTypeOption = [
	{ label: '全部', value: '' },
	{ label: '探店', value: 1 },
	{ label: '素材圈', value: 2 }
];
const channelOption = [
	{ label: '全部', value: '' },
	{ label: '达人营小程序', value: 1 },
	{ label: '达人营App', value: 2 }
];
const configOptions = ref([]); //事业群：
const locationOptions = ref([]); //站点ID

const locationconAll = async () => {
	configOptions.value = [];

	let params = {
		admin: roleIsAdmin.value ? 1 : 0
	};
	//事业群
	let res = await locationconfAll(params);
	if (res && res.code === 200) {
		let list = res.data || [];
		configOptions.value = list.map((item) => {
			item.label = item.name;
			item.value = item.configId;
			return item;
		});
	}
	configOptions.value.unshift({
		label: '全部',
		value: ''
	});
};
const locationList = async (configId = null) => {
	locationOptions.value = [];
	//站点列表
	let params = {
		city: '',
		configId: configId,
		admin: roleIsAdmin.value ? 1 : 0
	};

	let res = await locationAllList(params);
	let list = res.data || [];

	if (res && res.code === 200) {
		locationOptions.value = list.map((item) => {
			item.label = item.city;
			item.value = item.id;
			return item;
		});
	}
	locationOptions.value.unshift({
		label: '全部',
		value: ''
	});
};
const causeIdChange = (val) => {
	searchForm.locationId = '';
	locationList(val);
	getList();
};
watch(
	() => sort.value,
	(val) => {
		if (!val) return;
		if (!searchForm.locationId || !searchForm.positionType || !searchForm.channel) {
			message.error('站点、展示位置、投放渠道必填');
			sort.value = false;
		} else {
			getList();
		}
	}
);
const typeChange = (index) => {
	if (sort.value) return;
	typeCurrentIndex.value = index;
	searchForm.status = typeOptions[index].value;
	paginationReactive.page = 1;
	getList();
};

const addBanner = () => {
	router.push({
		path: '/bannerMange/addBanner',
		query: { admin: roleIsAdmin.value ? 1 : 0 }
	});
};
const seeHistoryBanner = () => {
	if (roleIsAdmin.value) {
		router.push({
			path: '/bannerMange/historyBannerAdmin'
		});
	} else {
		router.push({
			path: '/bannerMange/historyBanner'
		});
	}
};

const handelReset = () => {
	searchForm.keyWord = null;
	searchForm.channel = '';
	searchForm.configId = '';
	searchForm.locationId = '';
	searchForm.positionType = '';
	sort.value = false;
	paginationReactive.page = 1;
	getList();
};
const OfflineShow = ref(false);
const OfflineID = ref(null);
const ConfirmOffline = () => {
	if (!OfflineID.value) return;
	tdBannerOffline({ id: OfflineID.value }).then((res) => {
		if (res.code === 200) {
			paginationReactive.page = 1;
			message.success('操作成功');
			getList();
		}
	});
};
const Offline = (row) => {
	OfflineShow.value = true;
	OfflineID.value = row.bannerId;
};
const tableLoading = ref(false);
const paginationReactive = reactive({
	pageCount: 1,
	page: 1,
	pageSize: 10,
	showSizePicker: true,
	pageSizes: [10, 20, 50],
	itemCount: 0,
	prefix({ itemCount }) {
		return `共${itemCount}条`;
	},
	onChange: (page) => {
		paginationReactive.page = page;
		getList();
	},
	onPageSizeChange: (pageSize) => {
		paginationReactive.pageSize = pageSize;
		paginationReactive.page = 1;
		getList();
	}
});
const renderTooltip = (trigger, content) => {
	return h(NTooltip, null, {
		trigger: () => trigger,
		default: () => content
	});
};
// 默认表头
const defaultColumns = [
	{
		title: 'Banner ID',
		key: 'bannerId'
	},
	{
		title: 'Banner信息',
		key: 'bannerName',
		width: 180,
		render(row) {
			if (row.type == 1) {
				return [
					h('div', {}, `事业群：${row.configName ? row.configName : '暂无'}`),
					h('div', {}, `站点：${row.location ? row.location : '暂无'}`),
					h('div', {}, `产品ID：${row.productId ? row.productId : '暂无'}`),
					h('div', {}, `产品名称：${row.productName ? row.productName : '暂无'}`)
				];
			}
			return row.bannerName;
		}
	},
	{
		title: '图片',
		key: 'content',
		render(row) {
			return h(NImage, { width: '160', height: '100', src: row.content });
		}
	},
	{
		title: '创建时间',
		key: 'createTime',
		width: '200',
		render(row) {
			return [
				h('div', {}, `创建时间：${row.createTime ? row.createTime : '暂无'}`),
				h('div', {}, `展示时效：${row.startTime}-${row.endTime}`)
			];
		}
	},
	{
		title: '类型',
		key: 'type',
		render(row) {
			return h(
				'span',
				{},
				{
					default: () => {
						if (row.type === 1) {
							return '产品';
						} else if (row.type === 2) {
							return '自定义';
						}
					}
				}
			);
		}
	},
	{
		title: '状态',
		key: 'status',
		render(row) {
			return h(
				'div',
				{
					style: {
						borderRadius: '4px',
						background: 'rgba(179, 143, 143, 0.08)',
						lineHeight: '16px',
						fontSize: '12px',
						fontWeight: 600,
						color: row.status === 1 ? '#57AE59' : '#1D6FE9',
						width: '46px',
						paddingLeft: '5px'
					}
				},
				{
					default: () => {
						if (row.status === 1) {
							return '展示中';
						} else if (row.status === 2) {
							return '待展示';
						}
					}
				}
			);
		}
	},
	{
		title: '投放渠道',
		key: 'channel',
		render(row) {
			return h(
				'span',
				{},
				{
					default: () => {
						if (row.channel === 1) {
							return '达人营小程序 ';
						} else if (row.channel === 2) {
							return '达人营App';
						}
					}
				}
			);
		}
	},
	{
		title: '展示位置',
		key: 'positionType',
		render(row) {
			return h(
				'span',
				{},
				{
					default: () => {
						if (row.positionType === 1) {
							return '探店 ';
						} else if (row.positionType === 2) {
							return '素材圈';
						}
					}
				}
			);
		}
	},
	{
		title: '链接',
		key: 'linkUrl',
		render(row) {
			return h(
				'span',
				{
					style: {
						color: '#1D6FE9'
					}
				},
				`${row.linkUrl}`
			);
		}
	},
	{
		title: '曝光量',
		key: 'exposure',
		className: 'Tooltip',
		width: 120,
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '曝光量' }), '有效曝光人数（已去重）');
		}
	},
	{
		title: '点击量',
		key: 'click',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '点击量' }), '被点击人数（已去重）');
		}
	},
	{
		title: '点击率',
		key: 'clickRate',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '点击率' }), '点击量/曝光量');
		}
	},
	{
		title: '操作',
		key: 'actions',
		width: 100,
		render(row, index) {
			return buttonHandle(row, index);
		}
	}
];
//分析模式
const analysisColumns = [
	{
		title: 'Banner ID',
		width: 100,
		key: 'bannerId'
	},
	{
		title: 'Banner信息',
		key: 'bannerName',
		width: 180,
		render(row) {
			if (row.type == 1) {
				return [
					h('div', {}, `事业群：${row.configName ? row.configName : '暂无'}`),
					h('div', {}, `站点：${row.location ? row.location : '暂无'}`),
					h('div', {}, `产品ID：${row.productId ? row.productId : '暂无'}`),
					h('div', {}, `产品名称：${row.productName ? row.productName : '暂无'}`)
				];
			}
			return row.bannerName;
		}
	},
	{
		title: '图片',
		width: 150,
		key: 'content',
		render(row) {
			return h(NImage, { width: '160', height: '100', src: row.content });
		}
	},
	{
		title: '创建时间',
		key: 'createTime',
		width: '200',
		render(row) {
			return [
				h('div', {}, `创建时间：${row.createTime ? row.createTime : '暂无'}`),
				h('div', {}, `展示时效：${row.startTime}-${row.endTime}`)
			];
		}
	},
	{
		title: '类型',
		width: 120,
		key: 'type',
		render(row) {
			return h(
				'span',
				{},
				{
					default: () => {
						if (row.type === 1) {
							return '产品';
						} else if (row.type === 2) {
							return '自定义';
						}
					}
				}
			);
		}
	},
	{
		title: '状态',
		width: 100,

		key: 'status',
		render(row) {
			return h(
				'div',
				{
					style: {
						borderRadius: '4px',
						background: 'rgba(179, 143, 143, 0.08)',
						lineHeight: '16px',
						fontSize: '12px',
						fontWeight: 600,
						color: row.status === 1 ? '#57AE59' : '#1D6FE9',
						width: '46px',
						paddingLeft: '5px'
					}
				},
				{
					default: () => {
						if (row.status === 1) {
							return '展示中';
						} else if (row.status === 2) {
							return '待展示';
						}
					}
				}
			);
		}
	},
	{
		title: '投放渠道',
		width: 150,
		key: 'channel',
		render(row) {
			return h(
				'span',
				{},
				{
					default: () => {
						if (row.channel === 1) {
							return '达人营小程序 ';
						} else if (row.channel === 2) {
							return '达人营App';
						}
					}
				}
			);
		}
	},
	{
		title: '展示位置',
		width: 150,
		key: 'positionType',
		render(row) {
			return h(
				'span',
				{},
				{
					default: () => {
						if (row.positionType === 1) {
							return '探店 ';
						} else if (row.positionType === 2) {
							return '素材圈';
						}
					}
				}
			);
		}
	},
	{
		title: '链接',
		key: 'linkUrl',
		width: 150,
		render(row) {
			return h(
				'span',
				{
					style: {
						color: '#1D6FE9'
					}
				},
				`${row.linkUrl}`
			);
		}
	},
	{
		title: '曝光量 PV',
		width: 150,
		key: 'exposurePV',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '曝光量 PV' }), '有效曝光次数');
		}
	},
	{
		title: '曝光量UV',
		width: 150,
		key: 'exposureUV',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '曝光量UV' }), '有效曝光次数 (已去重)');
		}
	},
	{
		title: '人均曝光次数',
		width: 150,
		key: 'exposureAver',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '人均曝光次数' }), '曝光次数/曝光人数');
		}
	},
	{
		title: '点击量PV',
		width: 150,
		key: 'clickPV',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '点击量PV' }), '被点击次数');
		}
	},
	{
		title: '点击量UV',
		width: 150,
		key: 'clickUV',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '点击量UV' }), '被点击次数（已去重）');
		}
	},
	{
		title: '人均点击次数',
		width: 150,
		key: 'clickAver',

		className: 'Tooltip',
		title(column) {
			return renderTooltip(
				h('span', {}, { default: () => '人均点击次数' }),
				'可反应对用户的吸引度'
			);
		}
	},
	{
		title: '点击率',
		width: 150,
		key: 'clickRate',
		className: 'Tooltip',
		title(column) {
			return renderTooltip(h('span', {}, { default: () => '点击率' }), '点击量UV/曝光量UV');
		}
	},
	{
		title: '操作',
		key: 'actions',
		width: 120,
		fixed: 'right',
		render(row, index) {
			return buttonHandle(row, index);
		}
	}
];
const buttonHandle = (row, index) => {
	let actionsButton = [
		h(
			NButton,
			{
				size: 'small',
				text: true,
				type: 'primary',
				style: {
					display: 'block',
					fontSize: '14px',
					marginBottom: '16px'
				},
				onClick: () => handelBannerDetails(row)
			},
			{ default: () => '详情' }
		),
		h(
			NButton,
			{
				size: 'small',
				text: true,
				type: 'primary',
				style: {
					display: 'block',
					fontSize: '14px'
				},
				onClick: () => Offline(row)
			},
			{ default: () => '下线banner' }
		)
	];
	if (!sort.value) return actionsButton;
	let moveButton = [
		h(
			NButton,
			{
				size: 'small',
				text: true,
				type: 'primary',
				style:
					index === 0
						? {
								display: 'none'
						  }
						: {
								display: 'block',
								fontSize: '14px',
								marginTop: '16px'
						  },
				onClick: () => sortMove(3, row, index)
			},
			{ default: () => '置顶' }
		),
		h(
			NButton,
			{
				size: 'small',
				text: true,
				type: 'primary',
				style:
					index === 0
						? {
								display: 'none'
						  }
						: {
								display: 'block',
								fontSize: '14px',
								marginTop: '16px'
						  },
				onClick: () => sortMove(1, row, index)
			},
			{ default: () => '上移' }
		),
		h(
			NButton,
			{
				size: 'small',
				text: true,
				type: 'primary',
				style:
					index === tableData.value.length - 1
						? {
								display: 'none'
						  }
						: {
								display: 'block',
								fontSize: '14px',
								marginTop: '16px'
						  },
				onClick: () => sortMove(2, row, index)
			},
			{ default: () => '下移' }
		)
	];
	return [...actionsButton, ...moveButton];
};
const handelBannerDetails = (row) => {
	let params = {
		bannerId: row.bannerId
	};
	bannerDetailsRef.value.init(row.bannerId);
};
const sortMove = (type, row, index) => {
	// banner移动
	// type 1 上移 2下移 3置顶
	const params = {
		id: row.bannerId,
		locationId: searchForm.locationId,
		sortId: row.sortId,
		type: type
	};

	const moveSort = async () => {
		const res = await tdBannerMove(params);
		if (res.code === 200) {
			message.success('操作成功');
			getList();
		}
	};
	moveSort();
};

const tableData = ref([]);

const getList = async () => {
	tableLoading.value = true;
	const params = {
		...searchForm,
		listType: sort.value ? 2 : 1,
		pageIndex: paginationReactive.page,
		pageSize: paginationReactive.pageSize
	};
	let res;
	if (roleIsAdmin.value) {
		// 是否包含管理员
		res = await tdBannerList(params);
	} else {
		res = await areaTdBannerList(params);
	}
	if (res && res.code === 200) {
		tableData.value = res.data.productList;
		paginationReactive.itemCount = res.data.total;
	} else {
		tableData.value = [];
		paginationReactive.itemCount = 0;
	}
	tableLoading.value = false;
};

const init = async () => {
	hasRoles.value =
		router.currentRoute.value.meta?.roles && router.currentRoute.value.meta?.roles.length > 0; //路由角色
	if (hasRoles.value) {
		let roles = router.currentRoute.value.meta.roles;
		roleIsAdmin.value = roles.includes('Admin');
	} else {
		roleIsAdmin.value = false;
	}
	await locationconAll();
	await locationList();
	await getList();
};
nextTick(() => {
	init();
});
// 监听路由变化
watch(
	() => route.path,
	(val, oldValue) => {
		console.log(val, route);
		handelReset();
		init();
	}
);
</script>

<style lang="less" scoped>
.ll-page {
	height: 100%;
	display: flex;
	flex-direction: column;
	background-color: #ffffff;
	.banner-tips {
		padding: 10px 10px 0 10px;
		&-content {
			position: relative;
			padding: 17px 21px;
			z-index: 10;
			h1 {
				font-size: 18px;
				font-family: PingFangSC-Medium, PingFang SC;
				font-weight: 500;
				color: #333333;
				margin-bottom: 8px;
			}
			&-box {
				&-btn {
					cursor: pointer;
					color: #1d6fe9;
					font-size: 12px;
					text-decoration: underline;
				}
				&.close {
					overflow: hidden;
					white-space: nowrap;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
				}
				font-size: 12px;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #666666;
				line-height: 22px;
			}
			&-close {
				cursor: pointer;
				position: absolute;
				top: 0;
				right: 0;
				z-index: 20;
				width: 44px;
				height: 44px;
			}
			&-bg {
				position: absolute;
				left: 0;
				width: 100%;
				bottom: 0;
				height: 100%;
				z-index: -1;
			}
		}
	}
	&-query {
		background: @bg;
		padding: @padding-10;
		margin-right: 10px;
		margin-left: 10px;
		margin-top: 10px;
		border-radius: 3px;
		border: 1px solid #f0f0f0;
	}
	.type {
		padding: 10px;
		display: flex;
		&-box {
			display: flex;
			&-item {
				cursor: pointer;
				width: 80px;
				line-height: 36px;
				text-align: center;
				background: #f2f3f5;
				border: 1px solid #e5e5e5;
				font-size: 14px;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #4e5969;

				&.isActive {
					background: #ffffff;
					box-shadow: inset 0px -1px 0px 0px #ffffff;
					border-bottom: 1px solid transparent;
				}
				&.notClick {
					cursor: not-allowed;
					background: #f2f3f5;
					color: #c9cdd4;
				}

				&:nth-child(2) {
					border-left: none;
					border-right: none;
				}
			}
		}
		&-hr {
			flex: 1;
			border-bottom: 1px solid #e5e5e5;
		}
	}
	.mode-box {
		padding: 10px;
		display: flex;
		&-item {
			display: flex;
			align-items: center;
			margin-right: 20px;
			span {
				font-size: 14px;
				font-family: PingFangSC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
				padding-right: 8px;
			}
		}
	}

	&-table {
		padding: 10px;
		overflow: hidden;
		flex: 1 1 0%;
	}
}
</style>
